package com.mstore.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.mstore.pojo.Broadcast;

public class BroadcastDao extends SuperDao {

	/**
	 * 新增消息通知
	 */
	public void addBroadcast(Broadcast broadcast) {
		save(broadcast);
	}

	/**
	 * 删除消息通知
	 */
	public void delBroadcast(Broadcast broadcast) {
		delete(broadcast);
	}

	/**
	 * 修改消息通知
	 */
	public void modifyBroadcast(Broadcast broadcast) {
		String separate = " set ";
		StringBuilder sb = new StringBuilder();
		sb.append("update ubcenter.b_broadcast b");
		String title = broadcast.getTitle();
		if (StringUtils.isNotBlank(title)) {
			sb.append(separate);
			sb.append("b.title = '");
			sb.append(title);
			sb.append("'");
			separate = ", ";
		}

		String context = broadcast.getContext();
		if (StringUtils.isNotBlank(context)) {
			sb.append(separate);
			sb.append("b.context = '");
			sb.append(context);
			sb.append("'");
		}

		sb.append(" where b.br_id = ");
		sb.append(broadcast.getId());
		executeUpdate(sb.toString());
	}

	/**
	 * 分页查询企业的消息
	 */
	public List<Object> getBroadcastByPage(int index, long eaId) {
		StringBuilder sb = new StringBuilder();
		sb.append("from Broadcast where eaId = ");
		sb.append(eaId);
		sb.append(" order by createTime desc");
		return findPage(index, sb.toString());
	}

	/**
	 * 查询一条通知
	 */
	public Object getBroadcastById(Long id) {
		String sql = "from Broadcast where id = " + id;
		List<Object> list = find(sql);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}
	
	/**
	 * 获取企业的消息总数
	 */
	public int getCountBroadcastByEaId(Long eaId) {
		String sql = "select count(id) from Broadcast where eaId = ?";
		List<Object> obj = getObject(sql, new Object[] { eaId });
		if (obj.isEmpty()) {
			return 0;
		}
		return ((Long) obj.get(0)).intValue();
	}
	
	/**
	 * 条件查询消息
	 */
	public List<Object> getBroadcastByConditions(Broadcast broadcast) {
		StringBuilder sb = new StringBuilder();
		sb.append("from Broadcast");
		
		String separate = " where ";
		
		Long eaId = broadcast.getEaId();
		if (eaId != null) {
			sb.append(separate);
			sb.append("eaId = ");
			sb.append(eaId);
			separate = " and ";
		}
		
		Integer level = broadcast.getLevel();
		if (level != null) {
			sb.append(separate);
			sb.append("level = ");
			sb.append(level);
			separate = " and ";
		}
		
		sb.append(" order by createTime desc");
		
		Integer limit = broadcast.getLimit();
		Integer index = broadcast.getIndex();
		if (limit != null && index != null) {
			return findByLimit(index, limit, sb.toString());
		}
		
		return find(sb.toString());
	}

}
